package codename.carrot.bomberman.activity;

import sheep.game.Game;
import sheep.graphics.Image;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import codename.carrot.bomberman.AppStorage;
import codename.carrot.bomberman.BitmapFactory;
import codename.carrot.bomberman.R;
import codename.carrot.bomberman.StatsPreferences;

/**
 *  The main activity, which is the one containing the main menu and whatnot.
 * @author Group A4 
 */

public class MainActivity extends Activity implements OnClickListener {

	/**
	 * The shared preferences for stats.
	 */
	private SharedPreferences prefs;
	/**
	 * The button used to start the game lobby as a server.
	 */
	private Button btnHostGame, 
	/**
	 * The button used to start the game lobby as a client.
	 */
	btnJoinGame, 
	/**
	 * The button used for displaying the stats activity.
	 */
	btnMyStats, 
	/**
	 * Button to launch the about activity.
	 */
	btnAbout, 
	/**
	 * Button used for testing the gameplay locally.
	 */
	btnTestGame;
	/**
	 * The requst code returned used and returned by the wi-fi manager for starting as a server.
	 */
	public final static int WIFI_REQUEST_SERVER = 1880,
			/**
			 * The requst code returned used and returned by the wi-fi manager for starting as a client.
			 */
			WIFI_REQUEST_CLIENT = 1881;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		setContentView(R.layout.activity_main);

		btnHostGame = (Button) findViewById(R.id.btnHostGame);
		btnJoinGame = (Button) findViewById(R.id.btnJoinGame);
		btnMyStats = (Button) findViewById(R.id.btnMyStats);
		btnAbout = (Button) findViewById(R.id.btnAbout);
		btnTestGame = (Button) findViewById(R.id.btnTest);

		if(AppStorage.debuggingGame) {
		    btnTestGame.setVisibility(View.VISIBLE);
		}
		else {
		    btnTestGame.setVisibility(View.GONE);
		}
		
		btnHostGame.setOnClickListener(this);
		btnJoinGame.setOnClickListener(this);
		btnMyStats.setOnClickListener(this);
		btnAbout.setOnClickListener(this);
		btnTestGame.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		if (wifiManager.getConnectionInfo().getNetworkId() != -1)
			onWifiEnabled(requestCode);
	}

	/**
	 * Called when the wi-fi is enabled and connected on the system.
	 * @param requestCode The request code for starting a client or a server.
	 */
	private void onWifiEnabled(int requestCode) {
		if(requestCode == WIFI_REQUEST_SERVER)
			AppStorage.isClient = false;
		else
			AppStorage.isClient = true;
		
		this.onPlayerNameChange(prefs.getString("nickname", null));
	}

	@Override
	public void onClick(View v) {
	    AppStorage.testingGamePlay = false;
		if (v == btnHostGame || v == btnJoinGame) {
			//Check if client or host button was pressed.
			int requestCode = MainActivity.WIFI_REQUEST_CLIENT;
			if(v == btnHostGame)
				requestCode = MainActivity.WIFI_REQUEST_SERVER;
			
			//Check if Wi-Fi is enabled.
			WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
			if (wifiManager.getConnectionInfo().getNetworkId() == -1)
				this.startActivityForResult(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), requestCode);
			else
				onWifiEnabled(requestCode);
			
		} else if (v == btnMyStats) {
			Intent intent = new Intent(this, StatsActivity.class);
			startActivity(intent);
		} else if (v == btnAbout) {
			Intent intent = new Intent(this, AboutGameActivity.class);
			startActivity(intent);
		} else if (v == btnTestGame) {
		    GameActivity.gameInit = null;
		    GameActivity.players = null;
		    GameActivity.myPlayer = null;
		    AppStorage.testingGamePlay = true;
			Intent intent = new Intent(this, GameActivity.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	    AppStorage.droidPref = new StatsPreferences(getSharedPreferences(AppStorage.PREFERENCE_NAME, 0));
        AppStorage.droidGame = new Game(getApplicationContext(), null);
	    setupDroidGameConstants();
	    // Test levelReader
	    /*
	    LevelReader reader = new LevelReader(this);
	    try {
	        reader.readLevel("level1.ini");
	    }
	    catch(Exception e) {
	        Log.e("LEVEL", "Error reading level", e);
	    }*/
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent settingsActivity = new Intent(this, SettingsActivity.class);
		startActivity(settingsActivity);
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Called by the name changing dialog when a new nickname is typed.
	 * @param name The name to use in the game.
	 */
	private void onPlayerNameChange(String name) {
		if(name != null) {
			Intent intent;
			if (AppStorage.isClient)
				intent = new Intent(this, ClientGameLobbyActivity.class);
			else
				intent = new Intent(this, ServerGameLobbyActivity.class);
			intent.putExtra("nickname", name);
			startActivity(intent);
		} 
		else {
			new PlayerNameDialog(this);
		}
	}
	
	/**
	 * Set up constants used throghout the game.
	 */
	private void setupDroidGameConstants() {
		int width = getWindowManager().getDefaultDisplay().getWidth();
		int height = getWindowManager().getDefaultDisplay().getHeight();
		/* Because we're using landscape-mode for the game itself, and lets the user itself decide
		    which mode the other activities are in (based on screen rotation), we need to 
		    set the WIDTH and HEIGHT to the max, and min, of the two values we get from windowManager
		 */
        AppStorage.SCREEN_WIDTH_GAME = Math.max(width, height);
        AppStorage.SCREEN_HEIGHT_GAME = Math.min(width, height);
        
        /* Need to fetch a player image (any of them would do) to determine
            the size of the player ..
            TILE_SIZE, ITEM_SIZE and PLAYER_SIZE are ALL squares */
        Image playerImage = new Image(R.drawable.blue_1_d);
	    AppStorage.TILE_SIZE = (int) BitmapFactory.buildBoulderImage().getWidth();
	    AppStorage.ITEM_SIZE = AppStorage.TILE_SIZE - AppStorage.TILE_SIZE / 4;
	    AppStorage.PLAYER_SIZE = (int)playerImage.getWidth();
	}

	/**
	 * This class is responsible for creating a dialog and requesting the user to input a nickname for the game
	 * if it is not already set.
	 * @author Groupe A4
	 *
	 */
	private class PlayerNameDialog extends AlertDialog.Builder implements DialogInterface.OnClickListener {
		/**
		 * The text input field for editing the name.
		 */
		private EditText name;
		
		/**
		 * Construtcts and sets up the dialog with the calling context.
		 * @param arg0
		 */
		public PlayerNameDialog(Context arg0) {
			super(arg0);
			this.setTitle("Player name");
			this.name = new EditText(arg0);
			this.setView(name);
			this.setPositiveButton("Ok", this);
			this.setNegativeButton("Cancel", this);
			this.show();
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			String name = null;
			if (which == DialogInterface.BUTTON_POSITIVE) {
				name = this.name.getText().toString();
				Editor editor = prefs.edit();
				editor.putString("nickname", name);
				editor.commit();
				onPlayerNameChange(name);
			}
			dialog.dismiss();
		}
	}
}
